package com.hzhc.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzhc.annotation.SysTemLog;
import com.hzhc.dto.MemberVo;
import com.hzhc.dto.UserDto;
import com.hzhc.entity.SysUserSecurity;
import com.hzhc.entity.UserMember;
import com.hzhc.enumBean.LoginUserType;
import com.hzhc.enumBean.ResultUtilCodeEnum;
import com.hzhc.service.SysUserSecurityService;
import com.hzhc.service.UserMemberService;
import com.hzhc.utils.*;
import com.hzhc.vo.UserMemberVo;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author wuxiaoke
 * @description 会员登录
 * @date 2024/2/3 14:05
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/")
public class LoginUserMemberController {

    private final UserMemberService userMemberService;

    private final SysUserSecurityService sysUserSecurityService;

    @Value("${webSocketUrl}")
    private String webSocketUrl;

    @Value("${SSO.loginOutUrl}")
    private String loginOutUrl;

    @Value("${SSO.loginUrl}")
    private String loginUrl;

    @Value("${SSO.appId}")
    private String appId;

    @PostMapping("/login")
    @SysTemLog(operModul = "用户会员登录", operType = "用户会员登录", operDesc = "用户会员登录", modular = "PC")
    public  ResultUtil<UserMemberVo> userMemberLogin (HttpServletRequest request, HttpServletResponse response, Model model, @RequestBody UserMember userMember,
                        BindingResult bindingResult) {
        String loginname = userMember.getUsername();
        String password = userMember.getPassword();
        if (StrUtil.isBlank(loginname)) {
            return ResultUtil.build(null, ResultUtilCodeEnum.ACCOUNT_ERROR);
        }
        if (StrUtil.isBlank(password)) {
            return ResultUtil.build(null,ResultUtilCodeEnum.PASSWORD_ERROR);
        }
        UserMember userMember1 = userMemberService.getUserMember(loginname, password,1);
        UserMemberVo vo = new UserMemberVo();
        //处理 锁相关
        String msg=lockLogin(loginname, userMember1);
        if(StringUtils.isNotEmpty(msg)){
            List<SysUserSecurity> securities = sysUserSecurityService.getBaseMapper()
                    .selectList(new QueryWrapper<SysUserSecurity>().eq("status", 1).eq("disable",0));
            if(msg.indexOf("账号已锁")!=-1){
                vo.setShowMsg("账号已锁定,"+securities.get(0).getPasswordLockTime()+"分钟后再试");
            }else if(msg.indexOf("剩余")!=-1){//表示待锁账号
                vo.setShowMsg("用户名密码错误"+securities.get(0).getPasswordErrorNum()+"次,账号锁定"+securities.get(0).getPasswordLockTime()+"分钟");
            }
            return  ResultUtil.build(vo,400,msg);
        }
        if(userMember1 != null) {
            //获取用户所有角色
            String token = TokenUtil.signMemberToken(userMember1);
            BeanUtils.copyProperties(userMember1,vo);
            vo.setToken(token);
            vo.setUserType(LoginUserType.MEMBER.getCode());
            vo.setWebSocketUrl(webSocketUrl);
            //保存登录时间
            userMember1.setLastLoginTime(LocalDateTime.now());
            userMemberService.updateById(userMember1);
        }else {
            return ResultUtil.build(ResultUtilCodeEnum.USER_PASSWORD_ERROR);
        }
        return ResultUtil.build(vo,ResultUtilCodeEnum.SUCCESS);
    }

    private String lockLogin(String loginname, UserMember userMember) {
        if (userMember != null) {
            if(userMember.getLoginTime()!=null && userMember.getLoginTime().isAfter(LocalDateTime.now())){
                return "账号已锁!";
            }
            userMember.setLoginNum(0);
            userMember.setLoginTime(null);
            userMemberService.updateById(userMember);
            return "";
        }else{
            String msg=sysUserSecurityService.checkLoginFailure(loginname,"app",1);
            return msg;
        }
    }

//    @PostMapping("/auth/refreshToken")
//    public String refreshToken(HttpServletRequest request, @RequestBody JSONObject obj) {
//        String token = obj.getString("refresh_token");
//        if (StrUtil.isNotBlank(token)) {
//            return TokenUtil.refreshToken(token,LoginUserType.MEMBER.getCode());
//        }
//        return token;
//    }


    /**
     * 用户退出
     * @param request
     * @param response
     * @return ResultUtil<T>
     */
    @RequestMapping("/logout")
    @SysTemLog(operModul = "退出登录", operType = "退出", operDesc = "退出登录", modular = "PC")
    public ResultUtil<String> logout(HttpServletRequest request, HttpServletResponse response,@RequestBody UserDto userDto) {
        //删除用户的token数据
        UserMember user = new UserMember();
        user.setId( TokenUtil.getUserID(request));
        user.setSalt("");
        userMemberService.updateById(user);

        String loginOutResult = "";

        //调用SSO退出
        String appToken = userDto.getAppToken();
        String accessToken = userDto.getAccessToken();
        //凭借整体发送数据数据
        JSONObject logoutBodyJson = new JSONObject();
        logoutBodyJson.put("redirect_url", loginUrl);
        //组装发送头部
        HttpHeaders logoutHeard = new HttpHeaders();
        logoutHeard.setContentType(MediaType.APPLICATION_JSON);
        logoutHeard.set("app-token", appToken);
        logoutHeard.set("Accept-Certificate", appId);
        logoutHeard.set("Authorization", accessToken);
        //登出单点登录平台
        if (StrUtil.isNotBlank(appToken) && StrUtil.isNotBlank(accessToken)) {
            loginOutResult = HttpsPostUtil.sendHttpsPostJSON(loginOutUrl, logoutBodyJson, logoutHeard);
        }
        if (StrUtil.isNotBlank(loginOutResult)) {
            return ResultUtil.build("ssoLogOut",ResultUtilCodeEnum.LOGIN_OUT_SUCCESS);
        } else {
            return ResultUtil.build(null,ResultUtilCodeEnum.LOGIN_DD_OUT_SUCCESS);
        }

    }


    @PostMapping("/auth/refreshToken")
    public ResultUtil<String> refreshToken(HttpServletRequest request, @RequestBody JSONObject obj) {
        String token = obj.getString("refresh_token");
        if (StrUtil.isNotBlank(token)) {
            String newToken = TokenUtil.refreshToken(token, LoginUserType.USER.getCode());
            if( newToken== null){
                return ResultUtil.build(ResultUtilCodeEnum.TOKEN_ERROR);
            }else{
                return ResultUtil.build(newToken,ResultUtilCodeEnum.SUCCESS);
            }
        }
        return ResultUtil.build(ResultUtilCodeEnum.TOKEN_ERROR);
    }

}
